import { Component, OnDestroy, ViewChild, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, NgForm } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { UserDTO } from 'src/app/benshuo/model/user-dto';
import { FormUtil } from 'src/app/benshuo/util/form/form-util';

import { UserService } from 'src/app/benshuo/services/user.service';
import { SchoolSelectComponent } from '../../benshuo/component/school/school-select/school-select.component';

@Component({
  selector: 'passport-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.less'],
})
export class UserRegisterComponent implements OnDestroy, OnInit {
  /**
   * 调用api的标志
   */
  loading = false;

  /**
   * 用户信息
   */
  userDto: UserDTO = this.initFormData(null);

  /**
   * 系统配置信息编辑组件
   */
  @ViewChild('form', null)
  form: NgForm;

  /**
   * 学校下拉
   */
  @ViewChild('school', null)
  schoolSelectComponent: SchoolSelectComponent;

  /**
   * 密码等级 默认0
   */
  level = 0;

  /**
   * 初始化表单数据
   *
   * @param item 要初始化的数据，为null表示新建
   */
  private initFormData(item?: UserDTO): UserDTO {
    return {
      id: item ? item.id : null,
      account: item ? item.account : null,
      name: item ? item.name : null,
      password: item ? item.password : null,
      enabled: item ? item.enabled : null,
      mail: item ? item.mail : null,
      school: {
        id: null,
      },
      idCard: item ? item.idCard : null,
      major: item ? item.major : null,
      educational_institutions: item ? item.educational_institutions : null,
      grade: item ? item.grade : null,
    };
  }

  ngOnDestroy(): void {}
  ngOnInit(): void {
    // this.schoolSelectComponent.load();
  }

  constructor(private msg: NzMessageService, private userService: UserService, private router: Router) {}

  /**
   * 验证表单，如果通过则保存
   *
   * @param firstTime 是否第1次调用，是则调用表单验证
   */
  validate(firstTime: boolean): void {
    if (firstTime) {
      FormUtil.validateForm(this.form.form);
    }

    // 异步验证中
    if (this.form.form.status === 'PENDING') {
      setTimeout(() => {
        this.validate(false);
      }, 100);
    } else {
      // 结束验证
      if (this.form.form.valid) {
        this.save();
      }
    }
  }

  /**
   * 保存当前的数据，用于create或update
   */
  save(): void {
    // 验证表单
    if (this.level < 2) {
      this.msg.warning('密码强度太低');
      return;
    }
    if (!FormUtil.validateForm(this.form.form)) {
      return;
    }

    this.loading = true;
    this.userService.register(this.userDto).subscribe(
      data => this.afterItemSaved(),
      () => this.afterCallCompleted(),
      () => this.afterCallCompleted(),
    );
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(): void {
    this.loading = false;
    this.msg.success('注册成功!2秒后跳转登录页面');
    FormUtil.resetForm(this.form.form, this.userDto);
    setTimeout(() => {
      this.router.navigate(['/passport/login']);
    }, 2000);
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }
}
